package com.sylvek.sentinel.servlet;

import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.model.Point;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import com.sylvek.sentinel.Emergency;
import com.sylvek.sentinel.GoogleGeocodeResponse;
import com.sylvek.sentinel.GoogleGeocodeResult;
import com.sylvek.sentinel.PersistenceFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sylvek
 * 
 */
public class PublishAlert extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private static final String GOOGLE_REVERSE_API = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&latlng=";

    private static final String OK = "OK";

    private final Gson gson = new GsonBuilder().create();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        String name = req.getParameter("name");
        String text = req.getParameter("text");
        String postAddress = req.getParameter("postAddress");
        String category = req.getParameter("category");

        String latitude = req.getParameter("latitude");
        if (latitude == null) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        final double lat = Double.parseDouble(latitude);

        String longitude = req.getParameter("longitude");
        if (longitude == null) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        final double lon = Double.parseDouble(longitude);

        if (postAddress == null) {
            URL url = new URL(GOOGLE_REVERSE_API + latitude + "," + longitude);
            GoogleGeocodeResponse response = gson.fromJson(new JsonReader(new InputStreamReader(url.openStream())),
                    GoogleGeocodeResponse.class);

            if (response.getStatus().equals(OK)) {
                for (GoogleGeocodeResult result : response.getResults()) {
                    final String address = result.getFormatted_address();
                    if (address != null && !address.trim().equals("")) {
                        postAddress = address;
                        break;
                    }
                }
            }
        }

        final Emergency emergency = new Emergency();
        emergency.setName(name);
        emergency.setText(text);
        emergency.setLatitude(lat);
        emergency.setLongitude(lon);
        emergency.setTime(System.currentTimeMillis());
        emergency.setPostAddress(postAddress);
        emergency.setCategory(category);
        emergency.setGeocells(GeocellManager.generateGeoCell(new Point(lat, lon)));

        PersistenceFactory.getManager().makePersistent(emergency);

        resp.setHeader("Content-Type", "application/json; charset=iso-8859-15");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.getWriter().append(gson.toJson(emergency)).flush();
    }
}
